package com.image.fresco;

import android.app.ActivityManager;
import android.content.Context;
import android.graphics.PointF;
import android.net.Uri;

import com.facebook.cache.disk.DiskCacheConfig;
import com.facebook.common.memory.MemoryTrimType;
import com.facebook.common.memory.MemoryTrimmable;
import com.facebook.common.memory.MemoryTrimmableRegistry;
import com.facebook.common.memory.NoOpMemoryTrimmableRegistry;
import com.facebook.common.util.ByteConstants;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ImageDecodeOptions;
import com.facebook.imagepipeline.common.ImageDecodeOptionsBuilder;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.common.RotationOptions;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.qbw.log.XLog;

/**
 * @author qinbaowei
 * @createtime 2017/04/10 10:55
 * @email qbaowei@qq.com
 * @description
 */


public class FrescoUtil {

    private static Context sContext;

    public static void init(Context appContext) {
        sContext = appContext;
        //当内存紧张时采取的措施
        MemoryTrimmableRegistry memoryTrimmableRegistry = NoOpMemoryTrimmableRegistry.getInstance();
        memoryTrimmableRegistry.registerMemoryTrimmable(new MemoryTrimmable() {
            @Override
            public void trim(MemoryTrimType trimType) {
                //final double suggestedTrimRatio = trimType.getSuggestedTrimRatio();

                XLog.i("onCreate suggestedTrimRatio : %f", trimType.toString());
                if (MemoryTrimType.OnCloseToDalvikHeapLimit == trimType || MemoryTrimType.OnSystemLowMemoryWhileAppInBackground == trimType) {
                    XLog.w("清理fresco内存缓存");
                    Fresco.getImagePipeline().clearMemoryCaches();
                }
            }
        });
        ImagePipelineConfig pipelineConfig = ImagePipelineConfig.newBuilder(appContext)
                                                                .setDownsampleEnabled(true)
                                                                .setBitmapMemoryCacheParamsSupplier(
                                                                        new LolipopBitmapMemoryCacheSupplier(
                                                                                appContext))
                                                                .setMainDiskCacheConfig(
                                                                        DiskCacheConfig.newBuilder(
                                                                                appContext)
                                                                                       .setBaseDirectoryPath(
                                                                                               appContext
                                                                                                       .getCacheDir())
                                                                                       .setBaseDirectoryName(
                                                                                               "fresco")
                                                                                       .setMaxCacheSize(
                                                                                               256 * ByteConstants.MB)
                                                                                       .setMaxCacheSizeOnLowDiskSpace(
                                                                                               128 * ByteConstants.MB)
                                                                                       .setMaxCacheSizeOnVeryLowDiskSpace(
                                                                                               64 * ByteConstants.MB)
                                                                                       .build())
                                                                .setMemoryTrimmableRegistry(
                                                                        memoryTrimmableRegistry)
                                                                .setResizeAndRotateEnabledForNetwork(
                                                                        true)
                                                                .build();
        Fresco.initialize(appContext, pipelineConfig);
    }

    public static void loadImage(SimpleDraweeView simpleDraweeView, String url) {
        loadImage(simpleDraweeView, url, 0, 0, null);
    }

    public static void loadImage(SimpleDraweeView simpleDraweeView,
                                 String url,
                                 int width,
                                 int height) {
        loadImage(simpleDraweeView, url, width, height, null);
    }

    public static void loadImage(SimpleDraweeView simpleDraweeView,
                                 String url,
                                 ControllerListener<ImageInfo> controllerListener) {
        loadImage(simpleDraweeView, url, 0, 0, controllerListener);
    }

    public static void loadImage(SimpleDraweeView simpleDraweeView,
                                 String url,
                                 int width,
                                 int height,
                                 ControllerListener controllerListener) {
        if (url == null) {
            url = "";
        }
        loadImage(simpleDraweeView, Uri.parse(url), width, height, controllerListener);
    }


    public static void loadImage(SimpleDraweeView simpleDraweeView,
                                 Uri uri,
                                 int width,
                                 int height,
                                 ControllerListener controllerListener) {
        /*simpleDraweeView.getHierarchy().setActualImageFocusPoint(new PointF(0.5f, 0.2f));
        ImageDecodeOptions imageDecodeOptions = new ImageDecodeOptionsBuilder().setForceStaticImage(
                true).build();*/
        ImageRequestBuilder requestBuilder = ImageRequestBuilder.newBuilderWithSource(uri)
                                                                /*.setImageDecodeOptions(
                                                                        imageDecodeOptions)*/
                                                                .setRotationOptions(RotationOptions.autoRotate());
        if (width >= 0 && height >= 0) {
            int sw = width == 0 ? simpleDraweeView.getMeasuredWidth() : width;
            int sh = height == 0 ? simpleDraweeView.getMeasuredHeight() : height;
            XLog.v("load image %dx%d, path:%s", sw, sh, uri.toString());
            if (sw > 0 && sh > 0) {
                requestBuilder.setResizeOptions(new ResizeOptions(sw, sh));
            }
        } else {
            XLog.v("load image not resize, path:%s", uri.toString());
        }

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                                            .setOldController(simpleDraweeView.getController())
                                            .setImageRequest(requestBuilder.build())
                                            .setControllerListener(controllerListener)
                                            .build();
        simpleDraweeView.setController(controller);
    }

    public static Context getContext() {
        return sContext;
    }
}
